package com.webdrider.manager.action.snippet;

import java.util.ArrayList;
import java.util.List;

import com.common.dao.interfaces.IDao;
import com.common.dao.util.Criteria;
import com.common.dao.util.QueryOperation;
import com.common.manager.abstracts.AbstractManager;
import com.common.security.exceptions.DatabaseException;
import com.common.security.exceptions.ManagerException;
import com.webdrider.dao.action.snippet.DomainDao;
import com.webdrider.dao.interfaces.IDomainDao;
import com.webdrider.manager.interfaces.IDomainManager;
import com.webdrider.model.action.snippet.Domain;
import com.webdrider.security.exceptions.SnippetException;

public class DomainManager extends AbstractManager<Domain> implements IDomainManager {

	private IDomainDao dao;
	
	public DomainManager() {
		dao = new DomainDao();
	}
	
	@Override
	protected IDao<Domain> getDao() {
		return dao;
	}

	public Domain getDomain(String value) throws SnippetException, ManagerException {
		try {
			List<Criteria> criterias = new ArrayList<Criteria>();
			criterias.add(new Criteria(Domain.VALUE, value, QueryOperation.EQUALS, true));
			List<Domain> domains = dao.getByCriteria(criterias);

			if (domains.size() == 0) {
				throw new SnippetException(SnippetException.DOMAIN_NOT_FOUND);
			} else if (domains.size() == 1) {
				return domains.get(0);
			} else {
				throw new SnippetException(SnippetException.MULTIPLE_DOMAINS_FOUND);
			}
		} catch (DatabaseException e) {
			throw new ManagerException(ManagerException.DATABASE_EXCEPTION);
		}
	}
	
	public Domain getDomain(Long id) throws ManagerException {
		try {
			Domain domain = dao.getById(id);
			return domain;
		} catch (DatabaseException e) {
			throw new ManagerException(ManagerException.DATABASE_EXCEPTION);
		}
	}
	
	public boolean exist(String value) throws ManagerException {
		try {
			List<Criteria> criterias = new ArrayList<Criteria>();
			criterias.add(new Criteria(Domain.VALUE, value, QueryOperation.EQUALS, true));
			boolean exist = dao.getByCriteria(criterias).size() > 0;
			
			return exist;
		} catch (DatabaseException e) {
			throw new ManagerException(ManagerException.DATABASE_EXCEPTION);
		}
	}
}